package com.ls.blog.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.ls.blog.DTO.UserDetailsDTO;
import com.ls.blog.entity.UserAuth;
import com.ls.blog.entity.UserInfo;
import com.ls.blog.mapper.RoleMapper;
import com.ls.blog.mapper.UserAuthMapper;
import com.ls.blog.mapper.UserInfoMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;



/**
 * @program: securityByxml
 * @author: lishun
 * @create: 2021-06-29 11:02
 **/

/**
 * 自定义登录
 */

@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    @Autowired
    private UserAuthMapper userAuthMapper;

    @Autowired
    private UserInfoMapper userInfoMapper;



    @Resource
    private HttpServletRequest request;
    @Autowired
    private RoleMapper roleMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        if (StringUtils.isBlank(username)) {
            throw new UsernameNotFoundException("用户名不能为空！");
        }
        // 查询账号是否存在
        UserAuth userAuth = userAuthMapper.selectOne(new LambdaQueryWrapper<UserAuth>()
                .select(UserAuth::getId, UserAuth::getUserInfoId, UserAuth::getUsername, UserAuth::getPassword, UserAuth::getLoginType)
                .eq(UserAuth::getUsername, username));
        if (Objects.isNull(userAuth)) {
            throw new UsernameNotFoundException("用户名不存在!");
        }
        // 查询账号角色
        List<String> roleList = roleMapper.listRolesByUserInfoId(userAuth.getId());

        // 封装登录信息
        return convertLoginUser(userAuth, roleList, request);
    }

    // 结果封装
    public static UserDetails convertLoginUser(UserAuth user, List<String> roleList,HttpServletRequest request){
        List<SimpleGrantedAuthority> authorities = new ArrayList<>();
        for (String role : roleList) {
            authorities.add(new SimpleGrantedAuthority(role));
        }

        // 包装
        return UserDetailsDTO.builder().id(user.getId()).username(user.getUsername()).password(user.getPassword()).authorities(authorities).build();
    }
}

